<template>
  <!-- <pageTabelLayout> -->
  <!-- <template #pageHeader> -->
  <div class="search-form isheader" v-if="headerShow">
    <div>
      <a-form
        size="small"
        :model="pageData"
        layout="inline"
        v-if="permissionStore.hasPermisson('ybdj.cx')"
      >
        <a-form-item label="编号">
          <a-input
            allow-clear
            :style="{ width: '200px' }"
            class="bacClass"
            placeholder=""
            v-model="pageData.dropDownData"
            @press-enter="huiche"
          />
        </a-form-item>
      </a-form>
    </div>
    <div>
      <Toolbar
        :items="pageData.btnList"
        @add="addHandler"
        @import="importHandler"
        @del="deleteHandler"
        @select="selectHandler"
        @export="exports"
        @excel="downloadHandler"
      >
      </Toolbar>
    </div>
  </div>
  <div class="my-divisders">
    <a-divider orientation="center">
      <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
      <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
    </a-divider>
  </div>
  <div class="my-tool-bar"> </div>
  <div ref="tableRef">
    <a-spin
      :loading="pageData.pageLoading"
      tip="加载中"
      dot
      style="height: 100%; width: 100%; z-index: 999"
    >
      <AgGridVuesCopys
        :rowHeight="33"
        :headerHeight="33"
        :suppressCopyRowsToClipboard="true"
        :suppressDragLeaveHidesColumns="true"
        rowSelection="multiple"
        @grid-ready="gridReady"
        style="height: 600px"
        :defaultColDef="defaultColDef"
        class="ag-theme-alpine"
        :rowData="table.dataList"
        :columnDefs="tc"
        :localeText="localeText1"
        @columnResized="onColumnResized"
        @columnMoved="onColumnMoved"
        @columnVisible="onColumnVisible"
      ></AgGridVuesCopys>
    </a-spin>
    <!-- </template> -->
    <paginationCopys
      :total="total"
      show-total
      show-jumper
      show-page-size
      @change="PageSize"
      @page-size-change="change1"
      style="justify-content: center"
      :page-size="pagination.pageSize"
      :current="pagination.page"
      :page-size-options="pagingList1"
    />
  </div>

  <a-drawer
    style="z-index: 999"
    ok-text="保存"
    cancel-text="关闭"
    :drawer-style="{ zIndex: 9999 }"
    :mask-closable="false"
    :width="400"
    :visible="pageData.showAdd"
    unmountOnClose
    @ok="sideOk"
    @cancel="pageData.showAdd = false"
    :ok-loading="pageData.pageLoading"
  >
    <template #title>
      {{ pageData.sideTitle }}
    </template>
    <div>
      <a-form
        ref="formRef"
        layout="horizontal"
        :model="dataForm"
        :label-col-props="{ span: 7 }"
        :wrapper-col-props="{ span: 17 }"
      >
        <a-form-item
          label="验布等级"
          field="verifyclothLevel"
          :validate-trigger="['change', 'blur']"
          :rules="[{ required: true, message: '验布等级必填' }]"
        >
          <a-input class="bacClass" placeholder="" v-model="dataForm.verifyclothLevel" />
        </a-form-item>
        <a-form-item label="岗位" field="postName">
          <a-select popup-container="html" class="bacClass" v-model="dataForm.postName">
            <a-option value="全部">全部</a-option>
            <a-option value="验布工">验布工</a-option>
            <a-option value="验布班长">验布班长</a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="备注" field="remark">
          <a-textarea
            class="bacClass"
            placeholder=""
            v-model="dataForm.remark"
            :max-length="400"
            allow-clear
            show-word-limit
          />
        </a-form-item>
      </a-form>
    </div>
  </a-drawer>
</template>

<script lang="ts">
  import { post } from '@/api/http'
  import {
    useTable,
    useRowKey,
    useTableColumn,
    usePagination,
    useRowSelection,
  } from '@/hooks/table'
  import { localeText } from '@/api/aggridZw'
  import { ref, reactive, onMounted, onActivated, onUnmounted, onDeactivated } from 'vue'
  import Toolbar from '@/components/Toolbar.vue'
  import { Form, Message, Modal } from '@arco-design/web-vue'
  import { FormInstance } from '@arco-design/web-vue/es/form'
  import emitter from '@/hooks/useEventBus'
  import validate from '@/hooks/useValidate'
  import { DatasetComponent } from 'echarts/components'
  import { baseURL } from '../../../api/axios.config'
  import axios from 'axios'
  import usePermission from '@/store/modules/permission'
  
  import filedownload from 'js-file-download'
  import { pagingList } from '@/api/paging'
  import { useTableHeight } from '@/hooks/useTableHeight'
  import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
  interface DefectName {
    verifyclothLevel: string | undefined
    // seriaNumber: any
    createTime: string | undefined
    updateTime: string | undefined
    id: any
    updateName: string | undefined
    createName: string | undefined
    deleteState: number | undefined
    remark: string | undefined
    postName: string
  }

  export default {
    name: 'ClothInspectionGrade',
    setup() {
      //查询
      const headerShow = ref<boolean>(true)
      const scrollbar = ref(true)
      const total = ref(0)
      const page = ref(1)
      const size = ref(10)
      function PageSize(val: any) {
        pagination.page = val
        doRefresh()
      }

      function change1(val: any) {
        pagination.pageSize = val
        doRefresh()
      }

      function doRefresh() {
        pageData.pageLoading = true
        updateGridState01()
        post({
          url: 'qms/verifyClothLevel/selectVerifyclothLevelPage',
          data: {
            page: pagination.page,
            size: pagination.pageSize,
            deleteState: 0,
            verifyclothLevel: pageData.dropDownData,
          },
        })
          .then(({ data, code }: any) => {
            if (code === 200) {
              table.handleSuccess(data.list)
              //pagination.setTotalSize(data.total);
              gridOption.value.setRowData(data.list)
              total.value = data.total
            }
          })
          .catch(console.log)
          .finally(() => {
            pageData.pageLoading = false
          })
      }

      const { selectedRowKeys, onSelectionChange } = useRowSelection()
      const pagination = usePagination(doRefresh)
      const table = useTable()
      const rowKey = useRowKey('id')
      //检验表单是否含有中文的方法
      const hasChiese = validate.includeChinese
      const tableColumns = useTableColumn([
        {
          title: '序号',
          key: 'seriaNumber',
          dataIndex: 'seriaNumber',
          width: 150,
        },
        {
          title: '验布等级',
          key: 'verifyclothLevel',
          dataIndex: 'verifyclothLevel',
          width: 150,
        },
        {
          title: '岗位',
          key: 'postName',
          dataIndex: 'postName',
          width: 150,
        },
        {
          title: '备注',
          key: 'remark',
          dataIndex: 'remark',
          width: 150,
        },
        {
          title: '创建人',
          key: 'createName',
          dataIndex: 'createName',
          width: 150,
        },
        {
          title: '创建时间',
          key: 'createTime',
          dataIndex: 'createTime',
          width: 200,
        },
        {
          title: '最后修改人',
          key: 'updateName',
          dataIndex: 'updateName',
          width: 150,
        },
        {
          title: '最后修改时间',
          key: 'updateTime',
          dataIndex: 'updateTime',
          width: 200,
        },

        {
          title: '操作',
          key: 'id',
          dataIndex: 'id',
          slotName: 'action',
          width: 150,
          fixed: 'right',
        },
      ])
      const scroll = {
        x: 2000,
        y: 200,
      }
      let tc: any[] = tableColumns.map((o) => {
        let obj = {
          headerName: o.title,
          field: o.key,
          pinned: o['fixed'],
          tooltipField: o.key,
        }
        obj['width'] = 250
        if (o.slotName === 'action') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = 'right'
          obj['width'] = 80
          obj['cellRenderer'] = {
            template: `<el-button style="color:#165dff;"  v-if="isEdit" link @click="a">修改</el-button>`,
            setup(props: any) {
              const isEdit = ref(pageData.isEdit)
              const a = () => {
                editHandler(props.params.data)
              }
              return {
                isEdit,
                a,
              }
            },
          }
        }

        return obj
      })

      let a = [
        {
          showRowGroup: 'hide_def',
          headerName: '',
          checkboxSelection: true,
          headerCheckboxSelection: true,
          pinned: 'left',
          width: 50,
          resizable: false,
          filter: false,
          sortable: false,
          minWidth: 50,
          maxWidth: 50,
          lockPosition: 'left',
        },
      ]
      tc = a.concat(tc)
      const tablediv = ref(null)
      const pageData = reactive<{
        DefectName: DefectName[]
        showAdd: boolean
        sideTitle: string
        dropDownData: any
        pageLoading: boolean
        height: number
        tablediv: any
        rHeight: number | undefined
        DefectNameList: []
        btnList: any[]
        isEdit: boolean
      }>({
        DefectName: [],
        showAdd: false,
        sideTitle: '新增验布等级',
        dropDownData: '',
        pageLoading: false,
        height: 0,
        tablediv: null,
        rHeight: 0,
        DefectNameList: [],
        btnList: [],
        isEdit: false,
      })
      //下拉框得到焦点
      const focusSel = () => {
        selCxAll({ seriaNumber: '' })
      }
      //下拉数据
      const options = ref<any>(pageData.DefectNameList)
      const loading = ref(false)
      const handleSearch = (value: any) => {
        if (value) {
          const ob = { seriaNumber: value }
          loading.value = true
          window.setTimeout(() => {
            selCxAll(ob)
            options.value = pageData.DefectNameList
            loading.value = false
          }, 200)
        } else {
          options.value = []
        }
      }

      //下拉框查询
      function selCxAll(val: any) {
        post({
          url: 'qms/verifyClothLevel/VerifyclothLevelValue',
          data: val,
        }).then(({ data, code }: any) => {
          if (code === 200) {
            // (data as string[]).splice(0, 0, "全部");
            pageData.DefectNameList = data
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }
      const tableRef = ref()
      const { tableHeight, setTableHeight, getTableHeight, removeResize } = useTableHeight(tableRef)
      onMounted(() => {
        emitter.on('refresh-ClothInspectionGrade', () => {
          // doRefresh();
          selCxAll({ seriaNumber: '' })
        })
        pageData.rHeight = document.getElementById('masterDataSettings')?.clientHeight
        //表格的高
        if (pageData.rHeight !== undefined) {
          pageData.rHeight = pageData.rHeight - 200
        }

        window.addEventListener('resize', () => {
          pageData.rHeight = document.getElementById('masterDataSettings')?.clientHeight

          //表格的高
          if (pageData.rHeight !== undefined) {
            pageData.rHeight = pageData.rHeight - 200
          }
        })
        doRefresh()
        //自适应高度
        setTableHeight()
        getTableHeight()
      })
      onUnmounted(() => {
        console.log(1)

        removeResize()
      })
      //查询
      const selectHandler = () => {
        pagination.page = 1
        doRefresh()
      }
      const queryData = reactive({
        clothType: '',
      })
      const addHandler = () => {
        for (var key in dataForm) {
          if (key === 'id') {
            dataForm[key] = null
          } else if (key === 'deleteState' || key === 'donationMoney' || key === 'deleteDonation') {
            dataForm[key] = 0
          } else {
            dataForm[key] = ''
          }
        }
        pageData.showAdd = true
        pageData.sideTitle = '新增验布等级'
        dataForm.postName = '全部'
      }
      const dataForm = reactive<DefectName>({
        verifyclothLevel: '',
        // seriaNumber: '',
        createTime: '',
        updateTime: '',
        id: null,
        updateName: '',
        createName: '',
        deleteState: 0,
        remark: '',
        postName: '',
      })
      // 表格准备事件
      const gridOption = ref()
      const colState = ref()
      const gridReady = (params: any) => {
        gridOption.value = params.api
        colState.value = params.columnApi
      }
      const formRef = ref<FormInstance>()
      const sideOk = () => {
        formRef.value?.validate().then((err) => {
          if (!err) {
            if (pageData.sideTitle === '新增验布等级') {
              pageData.pageLoading = true
              post({
                url: 'qms/verifyClothLevel/insert',
                data: [dataForm],
              })
                .then((res: any) => {
                  if (res.code === 200) {
                    formRef.value?.resetFields()
                    dataForm.postName = '全部'
                    pageData.showAdd = false

                    Message.success({
                      content: '新增成功',
                      duration: 5000,
                    })
                    doRefresh()
                  } else {
                    Message.error({
                      content: res.message,
                      duration: 5000,
                    })
                  }
                })
                .finally(() => {
                  pageData.pageLoading = false
                })
            } else {
              pageData.pageLoading = true
              post({
                url: 'qms/verifyClothLevel/update',
                data: [dataForm],
              })
                .then((res: any) => {
                  if (res.code === 200) {
                    formRef.value?.resetFields()
                    dataForm.postName = '全部'
                    pageData.showAdd = false

                    Message.success({
                      content: '修改成功',
                      duration: 5000,
                    })
                    doRefresh()
                  } else {
                    Message.error({
                      content: res.message,
                      duration: 5000,
                    })
                  }
                })
                .finally(() => {
                  pageData.pageLoading = false
                })
            }
          }
        })
      }
      const deleteHandler = () => {
        // if (selectedRowKeys.value.length === 0) {
        //     return;
        // }
        if (gridOption.value.getSelectedRows() === 0) {
          return
        }

        Modal.confirm({
          title: '系统提示',
          content: '确认删除选中的数据?',
          onOk() {
            pageData.pageLoading = true
            post({
              url: 'qms/verifyClothLevel/delete',
              // data: selectedRowKeys.value,
              data: gridOption.value.getSelectedRows().map((o: any) => {
                return o.id
              }),
            })
              .then(({ code, data }: any) => {
                if (code === 200) {
                  Message.success({
                    content: '删除成功',
                    duration: 5000,
                  })
                  pagination.page = 1
                  doRefresh()
                } else {
                  Message.error({
                    content: '修改失败',
                    duration: 5000,
                  })
                }
              })
              .finally(() => {
                pageData.pageLoading = false
              })
          },
        })
      }
      const editHandler = (record: DefectName) => {
        dataForm.id = record.id
        // dataForm.seriaNumber = record.seriaNumber
        dataForm.verifyclothLevel = record.verifyclothLevel
        dataForm.remark = record.remark
        dataForm.postName = record.postName
        pageData.sideTitle = '修改验布等级'
        pageData.showAdd = true
      }
      //判断是否填写了中文
      const isChiese = (value: string, cb: Function) => {
        return new Promise<void>((resolve) => {
          if (window.encodeURI(value).indexOf('%') !== -1) {
            cb('填写的值只能是英文数字组合或英文，数字！')
          }
          resolve()
        })
      }
      //input离开焦点 将小写转大写
      // const inputBlur = () => {
      //   dataForm.seriaNumber = dataForm.seriaNumber.toUpperCase()
      // }
      //导出
      const exports = () => {
        // if (selectedRowKeys.value.length === 0) {
        //     Message.error('请先勾选')
        //     return
        // }
        if (gridOption.value.getSelectedRows() === 0) {
          Message.error('请先勾选')
          return
        } else {
          //将表头拼接出来
          let head =
            '<th>编号</th><th>验布等级</th><th>备注</th><th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>'
          //拿到当前表格数据与勾选的行做筛选

          // let nowRow = table.dataList.filter(function (o) {
          //     return selectedRowKeys.value.indexOf(o["id"]) !== -1;
          // })
          let nowRow = gridOption.value.getSelectedRows()
          let body = ''
          nowRow.forEach(function (o: any) {
            body += '<tr><td>' + o['seriaNumber'] + '</td>'
            body += '<td>' + o['verifyclothLevel'] + '</td>'
            body += '<td>' + o['remark'] + '</td>'
            body += '<td>' + o['createName'] + '</td>'
            body += '<td>' + o['createTime'] + '</td>'
            body += '<td>' + o['updateName'] + '</td>'
            body += '<td>' + o['updateTime'] + '</td>'
            body += '</tr>'
          })
          tableToXlsx(head, '验布等级', body)
        }
      }

      function tableToXlsx(head: any, filename: any, body: any) {
        const uri = 'data:application/vnd.ms-excel;base64,',
          template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`

        const a = document.createElement('a')
        a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
        a.download = filename
        a.click()
        document.removeChild(a)
      }

      //模板下载
      const downloadHandler = () => {
        axios
          .get(baseURL + '/qms/verifyClothLevel/uploadModel', {
            responseType: 'blob',
            headers: {
              token: sessionStorage.getItem('USER-TOKEN-KEY'),
            },
          })
          .then((res) => {
            if (res.status === 200) {
              filedownload(res.data, '验布等级.xlsx')
            }
          })
        // window.open(baseURL + '/product/mercery/uploadMerceryModel')
      }
      //导入
      const importHandler = () => {
        const inputEle: HTMLInputElement = document.createElement('input')
        inputEle.type = 'file'
        inputEle.id = 'fileUploadExcel'
        inputEle.accept =
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
        inputEle.addEventListener('change', (e) => {
          const formData = new FormData()
          if (inputEle.files !== null) {
            formData.append('file', inputEle.files[0] || '')
          } else {
            Message.warning('未选择文件！')
            return
          }
          pageData.pageLoading = true
          axios
            .post(baseURL + '/qms/verifyClothLevel/importModelData', formData, {
              headers: {
                'Content-Type': 'multipart/form-data',
                token: sessionStorage.getItem('USER-TOKEN-KEY'),
              },
            })
            .then((result) => {
              if (result.data['code'] === 200) {
                Message.success('导入成功')
              } else {
                Message.error(result.data.message)
              }
            })
            .finally(() => {
              pageData.pageLoading = false
              doRefresh()
            })
        })
        inputEle.click()
      }
      //设置权限
      // ['查询', '新增', '删除', '导出', '导入']
      const permissionStore = usePermission()

      if (permissionStore.hasPermisson('ybdj.cx')) {
        pageData.btnList.push('查询')
      }
      if (permissionStore.hasPermisson('ybdj.xz')) {
        pageData.btnList.push('新增')
      }
      if (permissionStore.hasPermisson('ybdj.sc')) {
        pageData.btnList.push('删除')
      }
      if (permissionStore.hasPermisson('ybdj.dc')) {
        pageData.btnList.push('导出')
      }
      if (permissionStore.hasPermisson('ybdj.dr')) {
        pageData.btnList.push('导入')
      }
      if (permissionStore.hasPermisson('ybdj.mbxz')) {
        pageData.btnList.push('模板下载')
      }
      if (permissionStore.hasPermisson('ybdj.xg')) {
        pageData.isEdit = true
      }
      const handleChange = (_data: any) => {
        table.handleSuccess(_data)
      }
      const defaultColDef = {
        sortable: true,
        resizable: true,
        filter: true,
        // flex: 1
      }
      const localeText1: any = ref(localeText)
      const huiche = () => {
        doRefresh()
      }
      const pagingList1: any = ref(pagingList)

      const { saveGridState: saveGridState01, updateGridState: updateGridState01 } =
        saveOrUpdateGridState01('ClothInspectionGrade', gridOption, colState, tc)
      const onColumnMoved = () => {
        saveGridState01()
      }
      const onColumnResized = () => {
        saveGridState01()
      }
      const onColumnVisible = () => {
        saveGridState01()
      }
      return {
        saveOrUpdateGridState01,
        saveGridState01,
        updateGridState01,
        onColumnMoved,
        onColumnResized,
        onColumnVisible,
        colState,
        pagingList1,
        huiche,
        localeText1,
        PageSize,
        change1,
        scroll,
        scrollbar,
        tablediv,
        downloadHandler,
        importHandler,
        hasChiese,
        deleteHandler,
        sideOk,
        formRef,
        dataForm,
        addHandler,
        selectedRowKeys,
        pagination,
        tableColumns,
        table,
        rowKey,
        pageData,
        queryData,
        editHandler,
        selectHandler,
        options,
        loading,
        handleSearch,
        // inputBlur,
        isChiese,
        exports,
        focusSel,
        headerShow,
        handleChange,
        defaultColDef,
        tc,
        gridOption,
        gridReady,
        total,
        permissionStore,
        tableRef,
        setTableHeight,
        getTableHeight,
        tableHeight,
        removeResize,
      }
    },
    components: { Toolbar,  },
  }
</script>
<style scoped lang="less"></style>
